/* eslint-disable array-callback-return */
import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Input, message, Row, Col, Tabs, Spin } from 'antd';
import router from 'umi/router';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { urlParse } from '@/utils/utils';
import styles from '@/utils/utils.less';
import Invoice from './update/Invoice';
import MailingAddress from './update/Mailingaddress';
import Bank from './update/Bank';
import Contact from './update/Contact';

const FormItem = Form.Item;
const { TabPane } = Tabs;

@connect(({ supplier, loading }) => ({
  supplier,
  loading: loading.models.supplier,
}))
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      suppId: null,
      activeKey: '1',
      areaId: '',
    };
  }

  componentDidMount() {
    const { location } = this.props;

    const suppId = urlParse(location.search).suppId ? urlParse(location.search).suppId : null;
    const activeKey = urlParse(location.search).activeKey
      ? urlParse(location.search).activeKey
      : '1';
    const { dispatch, form } = this.props;
    dispatch({
      type: 'supplier/updateGet',
      payload: { suppId, activeKey },
    }).then(res => {
      this.setState({ suppId });
      if (res.success && res.data) {
        this.getDictList();
        this.setState({ areaId: res.data.areaId });
        const getFieldsList = form.getFieldsValue();
        Object.keys(getFieldsList).forEach(key => {
          if (res.data[key]) {
            form.setFieldsValue({ [key]: res.data[key] });
            if (key === 'areaId') {
              form.setFieldsValue({ [key]: res.data.areaName });
            }
          }
        });
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  }

  // 获取字典:
  // 当前页签SUPPER_DETAIL_TAB、纳税人类型、所属银行BANK_ID、性别GENDER、是否有小孩HAS_CHILD、
  getDictList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'supplier/queryDictItemsByCodes',
      payload: [
        'SUPPER_DETAIL_TAB',
        'MINI_INV_TYPE',
        'TAXPAYER_TYPE',
        'BANK_ID',
        'GENDER',
        'HAS_CHILD',
      ],
    });
  };

  // 匹配字典：下拉
  matchDict = (list, id) => {
    let dict = null;
    list.map(item => {
      if (item.itemCode === id) {
        dict = item.itemCode;
      }
    });
    return dict;
  };

  // 切换页签
  changeTabPane = activeKey => {
    this.setState({ activeKey });
    const { suppId } = this.state;
    router.push(`/salemanage/supplier/update?suppId=${suppId}&activeKey=${activeKey}`);
  };

  // 取消
  cancel = () => {
    router.push(`/salemanage/supplier/index`);
  };

  // 提交
  sumSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { suppId, areaId } = this.state;
    const data = {};
    let submitData = {};
    form.validateFieldsAndScroll((error, values) => {
      if (!error) {
        Object.keys(values).forEach(key => {
          if (values[key] && values[key].key) {
            data[key] = values[key].key;
          } else {
            data[key] = values[key] ? values[key] : '';
          }
        });

        data.areaId = areaId;
        submitData = { ...data, suppId };
        dispatch({
          type: 'supplier/update',
          payload: submitData,
        }).then(res => {
          if (res.success) {
            message.success(`${res.message || '修改成功！'}`, 2, () => {
              router.push('/salemanage/supplier/index?activeKey=2');
            });
          } else {
            message.warning(`${res.message || '修改失败！'}`);
          }
        });
      }
    });
  };

  render() {
    const { suppId, activeKey } = this.state;
    const {
      supplier: { updateTabList, taxerTypeList, bankList, genderList, hasChildList },
      loading,
    } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    // 下拉选项
    const BasicInfo = (
      <div>
        <Form layout="vertical">
          <Row gutter={64}>
            <FormItem label="版本号" style={{ display: 'none' }}>
              {getFieldDecorator('vno', {
                rules: [{ required: true, message: '请输入' }],
                initialValue: 1,
              })(<Input placeholder="请输入" />)}
            </FormItem>
            <Col {...colProps}>
              <FormItem label="供应商名称">
                {getFieldDecorator('name', {
                  rules: [{ required: true, message: '请输入' }],
                })(<Input placeholder="请输入" disabled maxLength="100" />)}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="统一社会信用代码">
                {getFieldDecorator('uniCreditCode', {
                  rules: [{ required: true, message: '请输入' }],
                })(<Input placeholder="请输入" disabled maxLength="18" />)}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="地区">
                {getFieldDecorator('areaId', {
                  rules: [{ required: true, message: '请选择' }],
                })(<Input placeholder="请输入" disabled />)}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="办公地址">
                {getFieldDecorator('officeAddr', {})(
                  <Input placeholder="请输入" maxLength="100" />
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="联系电话">
                {getFieldDecorator('tel', {
                  rules: [
                    {
                      message: '请正确输入手机号码或固话(最大限制12位)',
                      pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,12}$/,
                    },
                  ],
                })(<Input placeholder="请输入" maxLength="12" />)}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="工作邮箱">
                {getFieldDecorator('email', {
                  rules: [{ type: 'email', message: '应为邮箱格式' }],
                })(<Input placeholder="请输入" maxLength="50" />)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={64}>
            <Col {...colProps}>
              <FormItem label="备注">
                {getFieldDecorator('remark', {})(<Input placeholder="请输入" />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div
          style={{
            marginTop: 100,
            paddingTop: 24,
            marginBottom: 16,
            textAlign: 'right',
            boxShadow: '0 -1px 2px rgba(0, 0, 0, 0.03)',
            borderTop: '1px solid #e8e8e8',
          }}
        >
          <Button onClick={() => this.cancel()} style={{ marginRight: 10 }}>
            取消
          </Button>
          <Button type="primary" onClick={this.sumSubmit}>
            提交
          </Button>
        </div>
      </div>
    );
    // 获取页签组件
    const getTabPane = activeKeys => {
      switch (activeKeys) {
        case '1':
          return BasicInfo;
        case '2':
          return <Invoice suppId={suppId} taxerTypeList={taxerTypeList} />;
        case '3':
          return <MailingAddress suppId={suppId} />;
        case '4':
          return <Bank suppId={suppId} bankList={bankList} />;
        case '5':
          return <Contact suppId={suppId} genderList={genderList} hasChildList={hasChildList} />;
        default:
          return <div />;
      }
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.tabCard}>
          <Spin tip="Loading..." spinning={loading}>
            <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
              {updateTabList.map(pane => (
                <TabPane tab={pane.itemName} key={pane.itemCode}>
                  {getTabPane(pane.itemCode)}
                </TabPane>
              ))}
            </Tabs>
          </Spin>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
